import type { Router } from "express";
import type { Ioracle, IcallbackFn } from "../../types";
import { decrypt } from "../../utils/privateKey";

const CourseList = (
  router: Router,
  oracle: Ioracle,
  callbackFn: IcallbackFn
) => {
  router.post("/getdata", (_req, res) => {
    const { dept } = _req.body;
    let sql = ` select a.rowid,a.dept_code,a.unit_code,a.unit_desc,a.train_hour,a.train_instruction,b.chinese_name created_by from xxcc_new_engineer_trainlist a,user_info_n b
     where a.dept_code = '${dept}' and a.created_by = b.account order by a.unit_code `;
    callbackFn(res, oracle.connHrm, { sql });
  });

  router.post("/addcourse", async (_req, res) => {
    let { para } = _req.body;
    para = JSON.parse(para);
    if (para.type === "add") {
      let sql = `select count(*) c_count from xxcc_new_engineer_trainlist where unit_code = '${para.unit_code}' and dept_code = '${para.dept_code}'`;
      const result1 = await oracle.connHrm({ sql });
      if (Number(result1.data[0].c_count) > 0) {
        res.send({ code: 0, message: "该单位已存在该课程" });
        return;
      }
      sql = ` insert into xxcc_new_engineer_trainlist(dept_code,unit_code,unit_desc,train_hour,train_instruction,created_by,created_date) 
    values('${para.dept_code}','${para.unit_code}','${para.unit_desc}',${
        para.train_hour
      },'${para.train_instruction}','${decrypt(para.created_by)}',sysdate) `;
      const result2 = await oracle.connHrm({ sql });
      if (result2.code === 200) {
        sql = `select a.rowid,a.dept_code,a.unit_code,a.unit_desc,a.train_hour,a.train_instruction,b.chinese_name created_by from xxcc_new_engineer_trainlist a,user_info_n b
       where a.dept_code = '${para.dept_code}' and a.unit_code = '${para.unit_code}' and a.created_by = b.account order by a.unit_code`;
        callbackFn(res, oracle.connHrm, { sql });
      } else {
        res.send({ code: 0, message: "數據庫異常" });
      }
    } else if (para.type === "modify") {
      let sql = ` update xxcc_new_engineer_trainlist set train_hour = ${para.train_hour},train_instruction = '${para.train_instruction}'
         where dept_code = '${para.dept_code}' and unit_code = '${para.unit_code}' `;
      callbackFn(res, oracle.connHrm, { sql });
    }
  });

  router.post("/deletecourse",(req,res)=>{
    const {rowid} = req.body
    let sql = ` delete from xxcc_new_engineer_trainlist where rowid = '${rowid}' `
    callbackFn(res,oracle.connHrm,{sql})
  })

  return router;
};

export default CourseList;
